from typing import *


class Solution:

    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        if matrix is None or len(matrix)==0:
            return []
        m, n = len(matrix), len(matrix[0])
        i = 0
        a = 0
        s = 0
        ans = []
        x, y = 0, -1
        mul = -1
        while i < m * n:
            if a & 1 == 1:
                s += 1
                for _ in range(m - s):
                    x += 1 * mul
                    ans.append(matrix[x][y])
                    i += 1
            else:
                mul *= -1
                for _ in range(n - s):
                    y += 1 * mul
                    ans.append(matrix[x][y])
                    i += 1
            a += 1

        return ans
